package com.dahuyou.change.method.param;

//import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
import java.lang.instrument.Instrumentation;

public class MyPreMain {

    public static void premain(String agentArgs, Instrumentation instrumentation) {
        System.out.println("MyPreMain.premain agentArgs is: " + agentArgs);

        AgentBuilder agentBuilder = new AgentBuilder.Default();

        AgentBuilder.Transformer transformer = (builder, typeDescription, classLoader, javaModule) -> {
            builder = builder.visit(
                    Advice.to(MyByteBuddyAdvice.class)
                            .on(ElementMatchers.named("newSelectorManager")));
/*
        AgentBuilder.Transformer transformer = (builder, typeDescription, classLoader, javaModule) -> {
            builder = builder.visit(
                    Advice.to(MyByteBuddyAdvice.class)
                            .on(ElementMatchers.isMethod()
                                    .and(ElementMatchers.any())
                                    .and(ElementMatchers.not(ElementMatchers.nameStartsWith("main")))));
*/
            return builder;
        };

        agentBuilder = agentBuilder.type(ElementMatchers.nameStartsWith("com.dahuyou.change.method.param")).transform(transformer).asDecorator();

        //监听
        AgentBuilder.Listener listener = new AgentBuilder.Listener() {
            @Override
            public void onDiscovery(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }

            @Override
            public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b, DynamicType dynamicType) {
                System.out.println("onTransformation：" + typeDescription);
            }

            @Override
            public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }

            @Override
            public void onError(String s, ClassLoader classLoader, JavaModule javaModule, boolean b, Throwable throwable) {

            }

            @Override
            public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {

            }

        };
        // 将bytebuddy的插桩逻辑安装到instrument
        agentBuilder.with(listener).installOn(instrumentation);
    }

    /**
     * 有public static void premain(String agentArgs, Instrumentation instrumentation)这个方法，本方法不会被调用
     * @param agentArgs
     */
    public static void premain(String agentArgs) {}
}
